package org.jiamandan.com.strategy.impl.tram.listener;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jiamandan.com.constant.BizConstant;
import org.jiamandan.com.constant.JSYConstant;
import org.jiamandan.com.dto.JsyBasicDto;
import org.jiamandan.com.strategy.impl.tram.IJSYDZBasicListener;
import org.jiamandan.com.utils.JsyObjectUtil;
import org.springframework.stereotype.Service;


@Service(value = JSYConstant.Service.CMD_JSY_T00201_SERVICE)
@AllArgsConstructor
@Slf4j
public class JSYChargeListener implements IJSYDZBasicListener {

    @Override
    public void doExecute(String payload, ChannelHandlerContext ctx) throws Exception {
        log.info("嘉满电-JSY设备充电应答(CMD = T00201)：" + payload);
        JsyBasicDto jsyBasicDto = JsyObjectUtil.parse(payload);
        String[] items = StringUtils.split(jsyBasicDto.getData(), BizConstant.separator);
        log.info("嘉满电-JSY下发充电:订单号:" + Long.parseLong(items[0], 16) + "端口号" + items[1] + "是否成功:" + (items[2].equals("01") ? "成功" : "失败"));
        Long tradeNo = Long.parseLong(items[0], 16);
            if (items[2].equals("01")) {
                queryGunStatus(ctx);
            } else {
                log.info("响应开始充电");
            }
            log.info("更新充电状态");
        }


    private void queryGunStatus(ChannelHandlerContext ctx) {
        StringBuilder builder = new StringBuilder();
        builder.append("_" + JSYConstant.Cmd.S00003).append("/0002:00")
                .append("\r\n");
        log.info("嘉满电-JSY查询最新状态：" + builder.toString());
        ByteBuf buf = Unpooled.buffer(builder.toString().getBytes().length);
        buf.writeBytes(builder.toString().getBytes());
        ChannelFuture future = ctx.writeAndFlush(buf);
    }
}
